const axios = require('axios')
const { get, del, set } = require('../utils/cache')

module.exports = async (req, res, { TITLE, CACHE_KEY, URL }, cb) => {
    if (req.query.timestamp) {
        del(CACHE_KEY)
    }
    let data = get(CACHE_KEY)
    if (data) {
        res._op('success', 1, data)
        console.log('在缓存中获取');
    }
    else {
        try {
            const { data: result } = await axios.get(URL)
            const list = cb(result)
            const updateTime = new Date().getTime()
            data = {
                title: TITLE,
                total: list.length,
                list,
                updateTime
            }
            set(CACHE_KEY, data)
            res._op('success', 1, data)
            console.log('通过服务获取');
        } catch (error) {
            res._op(error)
        }
    }
}
